import Vue from 'vue';
import * as Sentry from '@sentry/browser';
import { Vue as VueIntegration } from '@sentry/integrations';
import { Integrations } from '@sentry/tracing';
import store from '@/store/index';

function flattenObjectKeys(st) {
  if (typeof st === 'object' && st !== null) {
    return Object.keys(st).reduce((o, k) => {
      const child = flattenObjectKeys(st[k]);
      if (typeof child === 'object' && child) {
        Object.keys(child).forEach(ck => {
          o[`${k}.${ck}`] = child[ck];
        });
      } else {
        o[k] = child;
      }
      return o;
    }, {});
  }
  return st;
}

function appendUserData(event, ...rest) {
  if (rest.length === 0) return event;
  if (!event.user) event.user = {};
  const data = flattenObjectKeys(rest.shift());
  if (data && typeof data === 'object') {
    Object.keys(data).forEach(k => {
      event.user[k] = data[k];
    });
  }
  return appendUserData(event, ...rest);
}

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.TARGET_ENV,
  release: process.env.GIT_COMMIT,
  integrations: [
    new VueIntegration({
      Vue,
      tracing: true,
      tracingOptions: {
        trackComponents: true,
        hooks: ['activate', 'mount', 'update']
      }
    }),
    new Integrations.BrowserTracing()
  ],

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,

  beforeSend(event) {
    appendUserData(event, store.state.user.state);
    return event;
  }
});
